package edu.drexel.jrexel2d.camera;

import java.util.List;

import edu.drexel.jrexel2d.gamestate.Level;
import edu.drexel.jrexel2d.objects2D.Backdrop;
import edu.drexel.jrexel2d.objects2D.Object2D;
import edu.drexel.jrexel2d.objects2D.Player;

public class Camera {

	private double cameraBorderThreshold = 0.8;

	public void updateCamera(Level level, int width, int height) {

		List<Player> players = level.getPlayers();
		List<Object2D> objectsToShift = level.getObjects();
		Backdrop backdrop = level.getBackdrop();

		// TODO: This needs some thought as to how to handle multiple
		// players...
		if (areAnyPlayersAtRightEdge(players, width)
				&& !areAnyPlayersAtLeftEdge(players, width)) { // shift
			// left
			if (backdrop.getWidth() + backdrop.getLocation().getX() <= width) {
				backdrop.shift(
						width
								- (backdrop.getWidth() + backdrop.getLocation()
										.getX()), 0);
				return;
			}

			shiftBackdrop(backdrop, -5, 0);
			shiftObjects(objectsToShift, -5, 0);
			// objectsToShift.remove(player);
		}
		if (areAnyPlayersAtLeftEdge(players, width)
				&& !areAnyPlayersAtRightEdge(players, width)) { // shift right
			if (backdrop.getLocation().getX() >= 0) {
				backdrop.setLocation(0, 0);
				return;
			}

			shiftBackdrop(backdrop, 5, 0);
			shiftObjects(objectsToShift, 5, 0);
			// objectsToShift.remove(player);
		}

	}

	/**
	 * Shifts all objects to the left.
	 */
	private void shiftObjects(List<Object2D> objectsToShift, int x, int y) {

		System.out.println("Invoking Camera shift: Shifting all objects.");
		for (Object2D object : objectsToShift) {
			object.shift(x, y);
		}
	}

	private void shiftBackdrop(Backdrop b, int x, int y) {
		b.shift(x, y);
	}

	private boolean areAnyPlayersAtRightEdge(List<Player> players, int width) {
		for (Player player : players) {
			// TODO: This needs some thought as to how to handle multiple
			// players...
			if (player.getLocation().getX() > width * cameraBorderThreshold) {
				return true;
			}
		}
		return false;
	}

	private boolean areAnyPlayersAtLeftEdge(List<Player> players, int width) {
		for (Player player : players) {
			if (player.getLocation().getX() < width
					* (1 - cameraBorderThreshold)) {
				return true;
			}
		}
		return false;
	}
}
